package net.zhengxinyun.performance.controller.indicators;


import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.CountryIndicatorsEntity;
import net.zhengxinyun.performance.entity.CountryScoreEntity;
import net.zhengxinyun.performance.entity.TokenEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.CountryIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryScoreFilter;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryScoreService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.warn.WarnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 县指标控制层
 *
 * @Auther: hyp
 * @Date: 2018/10/26 16:11
 */
@RestController
@RequestMapping("/countryIndicators")
public class CountryIndicatorsController {

    private CountryIndicatorsService countryIndicatorsService;

    private TokenService tokenService;

    private CountryScoreService countryScoreService;

    private UserService userService;

    private LoginService loginService;

    @Autowired
    private WarnService warnService;

    @Autowired
    public CountryIndicatorsController(CountryIndicatorsService countryIndicatorsService, TokenService tokenService, CountryScoreService countryScoreService, UserService userService, LoginService loginService) {
        this.countryIndicatorsService = countryIndicatorsService;
        this.tokenService = tokenService;
        this.countryScoreService = countryScoreService;
        this.userService = userService;
        this.loginService = loginService;
    }

    /**
     * 指标管理删除
     *
     * @param param
     * @return
     */
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str = countryIndicatorsService.delete(param.countryIndicatorsEntity);
            if (!"删除成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            } else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 指标管理修改
     *
     * @param param
     * @return
     */
    @PostMapping("/update")
    public Result<String> update(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            //根据传来的上级指标名设置上级指标id
            countryIndicatorsService.setIdByName(param.countryIndicatorsEntity.getSuperiorIndexId(), param.countryIndicatorsEntity.getDateTime(), param.countryIndicatorsEntity);
            int i = countryIndicatorsService.update(param.countryIndicatorsEntity);
            if (i == 1) {
                return ResultUtils.getSuccessResults();
            } else {
                return ResultUtils.getResults(Result.Status.ERROR, "更新失败，请联系管理员");
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 指标管理添加
     *
     * @param param
     * @return
     */
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            CountryIndicatorsFilter filter = new CountryIndicatorsFilter();
            if (param.countryIndicatorsEntity != null) {
                CountryIndicatorsEntity countryIndicatorsEntity = param.countryIndicatorsEntity;
                //根据传来的上级指标名设置上级指标id
                countryIndicatorsService.setIdByName(countryIndicatorsEntity.getSuperiorIndexId(), countryIndicatorsEntity.getDateTime(), countryIndicatorsEntity);
                int i = countryIndicatorsService.insert(countryIndicatorsEntity);
                if (i != 0) {
                    return ResultUtils.getSuccessResults();
                } else {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败，请联系管理员");
                }
            } else if (param.list != null) {
                for (CountryIndicatorsEntity countryIndicatorsEntity : param.list) {
                    filter.setIndexName(countryIndicatorsEntity.getIndexName());
                    filter.setDateTime(countryIndicatorsEntity.getDateTime());
                    filter.setIndexType(countryIndicatorsEntity.getIndexType());
                    if (countryIndicatorsService.query(filter).size() != 0) {
                        continue;
                    }
                    if (param.dateTime != null) {
                        countryIndicatorsEntity.setDateTime(param.dateTime);
                    }
                    if (StringUtils.isNotBlank(countryIndicatorsEntity.getSuperiorIndexId())) {
                        //根据传来的上级指标名设置上级指标id
                        countryIndicatorsService.setIdByName(countryIndicatorsEntity.getSuperiorIndexId(), countryIndicatorsEntity.getDateTime(), countryIndicatorsEntity);
                    }
                    int i = countryIndicatorsService.insert(countryIndicatorsEntity);
                    if (i == 0) {
                        return ResultUtils.getResults(Result.Status.ERROR, "添加失败，请联系管理员");
                    }
                }
                return ResultUtils.getSuccessResults();
            }
            return ResultUtils.getResults(Result.Status.ERROR);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 指标管理查询
     *
     * @param param
     * @return
     */
    @PostMapping("/query")
    public Result<HashMap<String, Object>> query(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryIndicatorsFilter.getPageSize() == 0) {
                param.countryIndicatorsFilter.setPageSize(10);
            }
            HashMap<String, Object> map = new HashMap<>();
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setIndexType("一级指标");
            List<CountryIndicatorsFilter> firstIndexList = countryIndicatorsService.query(countryIndicatorsFilter);
            map.put("firstIndex", firstIndexList);//给一级指标集合
            List<CountryIndicatorsFilter> list = countryIndicatorsService.query(param.countryIndicatorsFilter);
            if (list.size() == 0) {
                param.countryIndicatorsFilter.setPageNumber(param.countryIndicatorsFilter.getPageNumber() - 1);
                list = countryIndicatorsService.query(param.countryIndicatorsFilter);
            }
            for (CountryIndicatorsFilter filter : list) {
                if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                    CountryIndicatorsEntity countryIndicatorsEntity = countryIndicatorsService.queryById(Long.valueOf(filter.getSuperiorIndexId()));
                    if ("二级指标".equals(countryIndicatorsEntity.getIndexType())) {
                        countryIndicatorsEntity = countryIndicatorsService.queryById(Long.valueOf(countryIndicatorsEntity.getSuperiorIndexId()));
                    }
                    filter.setSuperiorIndexId(countryIndicatorsEntity.getIndexName());
                }
            }
            Double pageTotal = Util.intGetTotalPage(countryIndicatorsService.queryForCount(param.countryIndicatorsFilter), param.countryIndicatorsFilter.getPageSize());
            map.put("pageTotal", pageTotal);
            map.put("list", list);//根据条件查询集合
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 录入分数页查询
     *
     * @param param
     * @return
     */
    @PostMapping("/queryInspection")
    public Result<HashMap<String, Object>> queryInspection(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryIndicatorsFilter.getPageSize() == 0) {
                param.countryIndicatorsFilter.setPageSize(10);
            }
            HashMap<String, Object> map = new HashMap<>();
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setIndexType("一级指标");
            List<CountryIndicatorsFilter> firstIndexList = countryIndicatorsService.query(countryIndicatorsFilter);
            List<Map<String, Object>> indexList = countryIndicatorsService.getIndexMap(firstIndexList);
            map.put("indexMap", indexList);
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            if (!"admin".equals(userEntity.getUserPermissions())) {
                param.countryIndicatorsFilter.setMainUnit(userEntity.getUserDepartment());
            }
            List<CountryIndicatorsFilter> list = countryIndicatorsService.querySecondIndex(param.countryIndicatorsFilter);
            if (list.size() == 0) {
                param.countryIndicatorsFilter.setPageNumber(param.countryIndicatorsFilter.getPageNumber() - 1);
                list = countryIndicatorsService.querySecondIndex(param.countryIndicatorsFilter);
            }
            Double pageTotal = Util.intGetTotalPage(countryIndicatorsService.queryByTwoTableCount(param.countryIndicatorsFilter), param.countryIndicatorsFilter.getPageSize());
            map.put("pageTotal", pageTotal);
            map.put("list", list);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/queryAudit")
    public Result<HashMap<String, Object>> queryAudit(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryIndicatorsFilter.getPageSize() == 0) {
                param.countryIndicatorsFilter.setPageSize(10);
            }
            HashMap<String, Object> map = new HashMap<>();
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setIndexType("一级指标");
            List<CountryIndicatorsFilter> firstIndexList = countryIndicatorsService.query(countryIndicatorsFilter);
            List<Map<String, Object>> indexList = countryIndicatorsService.getIndexMap(firstIndexList);
            map.put("indexMap", indexList);
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            if (!"admin".equals(userEntity.getUserPermissions())) {
                param.countryIndicatorsFilter.setMainUnit(userEntity.getUserDepartment());
            }
            if (StringUtils.isBlank(param.countryIndicatorsFilter.getAudit())) {
                param.countryIndicatorsFilter.setAudit("6");
            }
            List<CountryIndicatorsFilter> list = countryIndicatorsService.queryForAudit(param.countryIndicatorsFilter);
            if (list.size() == 0) {
                param.countryIndicatorsFilter.setPageNumber(param.countryIndicatorsFilter.getPageNumber() - 1);
                list = countryIndicatorsService.queryForAudit(param.countryIndicatorsFilter);
            }
            Double pageTotal = Util.intGetTotalPage(countryIndicatorsService.queryForAuditCount(param.countryIndicatorsFilter), param.countryIndicatorsFilter.getPageSize());
            map.put("pageTotal", pageTotal);
            map.put("list", list);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 录入分数
     *
     * @param param
     * @return
     */
    @PostMapping("/insertScore")
    public Result<String> setScore(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            int i = 0;
            CountryScoreEntity countryScoreEntity = new CountryScoreEntity();
            //因为前端不想改传过来的对象，只能后台赋值
            countryScoreEntity.setIndicatorsId(param.countryIndicatorsEntity.getId().toString());
            countryScoreEntity.setDateTime(param.countryIndicatorsEntity.getDateTime());
            countryScoreEntity.setMonthTime(param.countryIndicatorsEntity.getMonthTime());
            countryScoreEntity.setScore(param.countryIndicatorsEntity.getScore());
            countryScoreEntity.setAlternateField1(param.countryIndicatorsEntity.getAlternateField1());
            CountryScoreFilter filter = new CountryScoreFilter();
            //同上
            filter.setIndicatorsId(param.countryIndicatorsEntity.getId().toString());
            filter.setMonthTime(param.countryIndicatorsEntity.getMonthTime());
            filter.setDateTime(param.countryIndicatorsEntity.getDateTime());
            List<CountryScoreFilter> list = countryScoreService.query(filter);
            if (list.size() != 0 && !"1".equals(list.get(0).getAudit()) && !"2".equals(list.get(0).getAudit())) {
                countryScoreEntity.setAudit("0");
                countryScoreEntity.setReason("");
                countryScoreEntity.setId(Long.valueOf(param.countryIndicatorsEntity.getAlternateField2()));
                i = countryScoreService.update(countryScoreEntity);
                if (i == 0) {
                    return ResultUtils.getResults(Result.Status.ERROR, "更新失败");
                }
            } else {
                countryScoreEntity.setAudit("0");
                i = countryScoreService.insert(countryScoreEntity);
                if (i == 0) {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败");
                }
            }
            String s = warnService.updateStatusById(Long.valueOf(countryScoreEntity.getIndicatorsId()));
            if (!"预警信息修改成功".equals(s)){
                return ResultUtils.getResults(Result.Status.ERROR,s);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }


}

class CountryIndicatorsParam {
    public CountryIndicatorsFilter countryIndicatorsFilter;
    public CountryIndicatorsEntity countryIndicatorsEntity;
    public TokenEntity tokenEntity;
    public List<CountryIndicatorsEntity> list;
    public String dateTime;
    public CountryScoreEntity countryScoreEntity;
    public CountryScoreFilter countryScoreFilter;
}
